#"rtsp://admin:123456qq@192.168.10.192/stream1"
# rtsp://admin:Admin123@192.168.100.103:554/Streaming/Channels/101
#rtsp://admin:Admin123@192.168.100.103:554/cam/realmonitor?channel=1&subtype=0

import time
import multiprocessing as mp
import cv2
import os

"""
Source: Yonv1943 2018-06-17
https://github.com/Yonv1943/Python
https://zhuanlan.zhihu.com/p/38136322
OpenCV official demo
https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html
海康、大华IpCamera RTSP地址和格式（原创，旧版）- 2014年08月12日 23:01:18 xiejiashu
rtsp_path_hikvison = "rtsp://%s:%s@%s/h265/ch%s/main/av_stream" % (user, pwd, ip, channel)
rtsp_path_dahua = "rtsp://%s:%s@%s/cam/realmonitor?channel=%d&subtype=0" % (user, pwd, ip, channel)
https://blog.csdn.net/xiejiashu/article/details/38523437
最新（2017）海康摄像机、NVR、流媒体服务器、回放取流RTSP地址规则说明 - 2017年05月13日 10:51:46 xiejiashu
rtsp_path_hikvison = "rtsp://%s:%s@%s//Streaming/Channels/%d" % (user, pwd, ip, channel)
https://blog.csdn.net/xiejiashu/article/details/71786187
"""


def image_put(q, user, pwd, ip, channel=1):
    # cap = cv2.VideoCapture("rtsp://%s:%s@%s/stream1" % (user, pwd, ip))
    # cap = cv2.VideoCapture("rtsp://%s:%s@%sStreaming/Channels/1701?transportmode=unicast" % (user, pwd, ip))

    # if cap.isOpened():
    #     print('HIKVISION')
    # else:
    #     cap = cv2.VideoCapture("rtsp://%s:%s@%s/cam/realmonitor?channel=%d&subtype=0" % (user, pwd, ip, channel))
    #     print('DaHua')
    cap = cv2.VideoCapture("rtsp://%s:%s@%s/h265/ch1/main/av_stream" % (user, pwd, ip))
    if cap.isOpened():
        print('HIKVISION')
    else:
        cap = cv2.VideoCapture("rtsp://admin:123456qq@192.168.100.12/stream1")
        print('Genius')

    while True:
        q.put(cap.read()[1])
        q.get() if q.qsize() > 1 else time.sleep(0.01)



def run_opencv_camera():
    user, pwd, ip, channel = "admin", "123456qq", "33.90.7.110", 1

    cap_path = 0  # local camera (e.g. the front camera of laptop)
    # cap_path = 'video.avi'  # the path of video file
    # cap_path = "rtsp://%s:%s@%s/h264/ch%s/main/av_stream" % (user, pwd, ip, channel)  # HIKIVISION old version 2015
    # cap_path = "rtsp://%s:%s@%s//Streaming/Channels/%d" % (user, pwd, ip, channel)  # HIKIVISION new version 2017
    # cap_path = "rtsp://%s:%s@%s/cam/realmonitor?channel=%d&subtype=0" % (user, pwd, ip, channel)  # dahua

    cap = cv2.VideoCapture(cap_path)

    while cap.isOpened():
        is_opened, frame = cap.read()
        cv2.imshow('frame', frame)
        cv2.waitKey(1000)
    cap.release()

def image_get_s(queue_list, ip, img_path):
    """show in single opencv-imshow window"""

    window_name1 = "%s" % ip[0]
    window_name2 = "%s" % ip[1]
    window_name3 = "%s" % ip[2]
    # window_name4 = "%s" % ip[3]

    idx_img = 0
    cv2.namedWindow(window_name1, flags=cv2.WINDOW_FREERATIO)
    cv2.namedWindow(window_name2, flags=cv2.WINDOW_FREERATIO)
    cv2.namedWindow(window_name3, flags=cv2.WINDOW_FREERATIO)
    # cv2.namedWindow(window_name4, flags=cv2.WINDOW_FREERATIO)
    while True:
        imgs = [q.get() for q in queue_list]
        img1 = imgs[0]
        img2 = imgs[1]
        img3 = imgs[2]
        # img4 = imgs[3]

        img1_tmp = cv2.resize(img1, (int(1920/2 ), int(1080/2 )))
        img2_tmp = cv2.resize(img2, (int(1920/2 ), int(1080/2 )))
        img3_tmp = cv2.resize(img3, (int(1920 / 2), int(1080 / 2)))
        # img4_tmp = cv2.resize(img4, (int(1920 / 2), int(1080 / 2)))

        cv2.imshow(window_name1, img1_tmp)
        cv2.imshow(window_name2, img2_tmp)
        cv2.imshow(window_name3, img3_tmp)
        # cv2.imshow(window_name4, img4_tmp)
        # imgs = np.concatenate(imgs, axis=1)
        # cv2.imshow(window_name, imgs)
        key = cv2.waitKey(1)

        if key == ord('s'):
            img_path0 = os.path.join(img_path[0], str(idx_img) + '.jpg')
            cv2.imwrite(img_path0, img1)

            img_path1 = os.path.join(img_path[1], str(idx_img) + '.jpg')
            cv2.imwrite(img_path1, img2)

            img_path2 = os.path.join(img_path[2], str(idx_img) + '.jpg')
            cv2.imwrite(img_path2, img3)

            # img_path3 = os.path.join(img_path[3], str(idx_img) + '.jpg')
            # cv2.imwrite(img_path3, img3)
            # idx_img += 1

def image_get_all(queue_list, ip, img_path):
    """show in single opencv-imshow window"""

    window_name1 = "%s" % ip[0]
    window_name2 = "%s" % ip[1]
    # window_name3 = "%s" % ip[2]
    # window_name4 = "%s" % ip[3]


    idx_img = 0
    while True:
        imgs = [q.get() for q in queue_list]
        img1 = imgs[0]
        img2 = imgs[1]
        # img3 = imgs[2]
        # img4 = imgs[3]

        img1_tmp = cv2.resize(img1, (int(1920/2 ), int(1080/2 )))
        img2_tmp = cv2.resize(img2, (int(1920/2 ), int(1080/2 )))
        # img3_tmp = cv2.resize(img3, (int(1920/4), int(1080/ 4)))
        # img4_tmp = cv2.resize(img4, (int(1920 / 4), int(1080 / 4)))
        # print('11',len(img1_tmp))
        cv2.imshow(window_name1, img1_tmp)
        cv2.imshow(window_name2, img2_tmp)
        # cv2.imshow(window_name3, img3_tmp)
        # cv2.imshow(window_name4, img4_tmp)

        cv2.waitKey(1)

        cv2.imwrite(img_path[0]+str(idx_img)+'.jpg', img1)
        cv2.imwrite(img_path[1]+str(idx_img)+'.jpg', img2)
        # cv2.imwrite(img_path[2]+str(idx_img)+'.jpg', img3)
        # cv2.imwrite(img_path[3]+str(idx_img) +'.jpg',img4)
        idx_img +=1


def run_single_camera():
    # user_name, user_pwd, camera_ip = "admin", "admin123456", "172.20.114.196"
    # user_name, user_pwd, camera_ip = "admin", "Admin123", "192.168.100.103:554"
    user_name, user_pwd, camera_ip = "admin", "Admin123", "192.168.100.100:554"

    
    mp.set_start_method(method='spawn')  # init
    queue = mp.Queue(maxsize=2)
    processes = [mp.Process(target=image_put, args=(queue, user_name, user_pwd, camera_ip)),
                 mp.Process(target=image_get_s, args=(queue, camera_ip))]

    [process.start() for process in processes]
    [process.join() for process in processes]


def run_multi_camera():
    user_name = "admin"

    camera_ip_l = [
        # "172.20.114.196",  # ipv4
        # "[fe80::3aaf:29ff:fed3:d260]",  # ipv6
        # "192.168.100.180:554",
        # "192.168.100.182:554",
        "192.168.1.64:554",
        "192.168.1.65:554",
    ]

    passwords = ['playtrac@1','playtrac@1']

    mp.set_start_method(method='spawn')  # init
    queues = [mp.Queue(maxsize=len(camera_ip_l)) for _ in camera_ip_l]


    imgs_path = []
    for i in range(len(camera_ip_l)):
        imgs_path.append("camera/{}/".format(camera_ip_l[i].split(':')[0]))
        if not os.path.exists(imgs_path[-1]):
            os.makedirs(imgs_path[-1])

    processes = [mp.Process(target=image_get_all, args=(queues, camera_ip_l, imgs_path))]

    for queue, camera_ip, img_path,pw in zip(queues, camera_ip_l, imgs_path, passwords):
        processes.append(mp.Process(target=image_put, args=(queue, user_name, pw, camera_ip)))



    for process in processes:
        process.daemon = True
        process.start()
    for process in processes:
        process.join()
    # p.join()

def image_collect(queue_list, camera_ip_l):
    import numpy as np

    """show in single opencv-imshow window"""
    window_name1 = "%s" % camera_ip_l[0]
    window_name2 = "%s" % camera_ip_l[1]
    cv2.namedWindow(window_name1,)
    cv2.namedWindow(window_name2)
    while True:
        imgs = [q.get() for q in queue_list]
        img1 = imgs[0]
        img2 = imgs[1]

        # cv2.imshow(window_name1, img1)
        # cv2.imshow(window_name2, img2)

        img1_tmp = cv2.resize(img1, (int(1920 / 2), int(1080 / 2)))
        img2_tmp = cv2.resize(img2, (int(1920 / 2), int(1080 / 2)))
        cv2.imshow(window_name1, img1_tmp)
        cv2.imshow(window_name2, img2_tmp)
        # imgs = np.concatenate(imgs, axis=1)
        # cv2.imshow(window_name, imgs)
        cv2.waitKey(1)

  

def run_multi_camera_in_a_window():
    user_name = "admin"
    camera_ip_l = [
        # "172.20.114.196",  # ipv4
        # "[fe80::3aaf:29ff:fed3:d260]",  # ipv6
        "192.168.1.64:554",
        "192.168.1.65:554"
    ]
    passwords = ['playtrac@1','playtrac@1']

    mp.set_start_method(method='spawn')  # init
    queues = [mp.Queue(maxsize=2) for _ in camera_ip_l]

    processes = [mp.Process(target=image_collect, args=(queues, camera_ip_l))]
    for queue, camera_ip,pw in zip(queues, camera_ip_l,passwords):
        processes.append(mp.Process(target=image_put, args=(queue, user_name, pw, camera_ip)))

    for process in processes:
        process.daemon = True  # setattr(process, 'deamon', True)
        process.start()
    for process in processes:
        process.join()



def get_biaoding():
    user, pwd, ip, channel = "admin", "Admin123", "192.168.100.182:554", 1
    cap = cv2.VideoCapture("rtsp://%s:%s@%s/cam/realmonitor?channel=%d&subtype=0" % (user, pwd, ip, channel))
    if cap.isOpened():
        print('HIKVISION')
    idx_img = 20
    img_folder = "D:/20210226/camera{}".format(ip.split('.')[-1].split(':')[0])
    if not os.path.exists(img_folder):
        os.makedirs(img_folder)
    while True:
        img = cap.read()[1]
        img_tmp = cv2.resize(img, (1920 // 2, 1080 // 2))
        cv2.imshow('image', img_tmp)
        key = cv2.waitKey(1)
        if key == ord('s'):
            img_path = os.path.join(img_folder, str(idx_img) + '.jpg')
            cv2.imwrite(img_path, img)
            idx_img += 1




def get_img():
    cap1 = cv2.VideoCapture("rtsp://%s:%s@%s/h265/ch1/main/av_stream" % ("admin", "playtrac@1", "192.168.1.65:554/"))
    # cap2 = cv2.VideoCapture("rtsp://%s:%s@%s/cam/realmonitor?channel=%d&subtype=0" % ("admin", "Admin123", "192.168.100.182:554/", 1))
    # cap3 = cv2.VideoCapture("rtsp://%s:%s@%s/cam/realmonitor?channel=%d&subtype=0" % ("admin", "Admin123", "192.168.100.183:554/", 1))
    # cap4 = cv2.VideoCapture("rtsp://%s:%s@%s/cam/realmonitor?channel=%d&subtype=0" % ("admin", "Admin123", "192.168.100.184:554/", 1))

    img_save1 = "E:/dataset_0902/calibrate_intri/181"
    # img_save1 = "D:/20210308/camera/181"
    # img_save2 = "D:/20210225/camera/182"
    # img_save3 = "D:/20210225/camera/183"
    # img_save4 = "D:/20210225/camera/184"
    # if not os.path.exists(img_save1):
    #     os.makedirs(img_save1)
    # if not os.path.exists(img_save2):
    #     os.makedirs(img_save2)
    # if not os.path.exists(img_save3):
    #     os.makedirs(img_save3)
    # if not os.path.exists(img_save4):
    #     os.makedirs(img_save4)

    if cap1.isOpened():
        print('HIKVISION')

    idx_img = 0
    while True:

        time1 = cap1.get(cv2.CAP_PROP_POS_MSEC)

        # print(time1)

        img1 = cap1.read()[1]
        if (img1 is None):
            print("ok")
            continue

        # cv2.imwrite(img_save1 + '/' + str(idx_img) + '.jpg', img1)
        idx_img = idx_img + 1


        # key = cv2.waitKey(1)
        # if key == ord('s'):
        #     cv2.imwrite()
        #     cv2.imwrite(iimg_save1 + '/' + str(idx_img) + '.jpg', img1mg_save2 + '/' + str(idx_img) + '.jpg', img2)
        #     cv2.imwrite(img_save3 + '/' + str(idx_img) + '.jpg', img3)
        #     cv2.imwrite(img_save4 + '/' + str(idx_img) + '.jpg', img4)
        #     idx_img += 1

        img1 = cv2.resize(img1, (int(1920 / 2), int(1080 / 2)))

        cv2.imshow('1', img1)
        cv2.waitKey(1)


if __name__ == '__main__':

    # get_biaoding()
    get_img()
    # 显示图片
    # run_multi_camera_in_a_window()
    # 保存图片
    # run_multi_camera()